package bard.partnermatchingsystem.controller;


import bard.partnermatchingsystem.Common.ErrorCode;
import bard.partnermatchingsystem.contant.UserConstant;
import bard.partnermatchingsystem.domain.R.R;
import bard.partnermatchingsystem.domain.dto.UserLoginDTO;
import bard.partnermatchingsystem.domain.dto.UserRegisterDTO;
import bard.partnermatchingsystem.domain.po.User;
import bard.partnermatchingsystem.domain.vo.UserVO;
import bard.partnermatchingsystem.exception.CommonException;
import bard.partnermatchingsystem.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin(origins = {"http://localhost:3000"})
@RequestMapping("/user")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Resource
    private RedisTemplate<String, Object>  redisTemplate;
    @PostMapping("/register")
    public R<Long> UserRegister(@RequestBody UserRegisterDTO userRegisterDTO) {
        if (userRegisterDTO == null){
            throw new CommonException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterDTO.getUserAccount();
        String password = userRegisterDTO.getPassword();
        String checkPassword = userRegisterDTO.getCheckPassword();
        String planetCode = userRegisterDTO.getPlanetCode();
        if(StringUtils.isAnyBlank(userAccount,password,checkPassword)){
            throw new CommonException(ErrorCode.PARAMS_ERROR);
        }
        long i = userService.UserRegister(userAccount, password, checkPassword, planetCode);
        return R.ok(i);
    }

    @PostMapping("/login")
    public R<User> doLogin(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request) {
        if (userLoginDTO == null){
            return null;
        }
        String userAccount = userLoginDTO.getUserAccount();
        String password = userLoginDTO.getUserPassword();
        if(StringUtils.isAnyBlank(userAccount,password)){
            return null;
        }
        User user = userService.doLogin(userAccount, password, request);
        return R.ok(user);
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @PostMapping ("/logout")
    public R<Integer> doLogout(HttpServletRequest request) {
        if (request == null) {
            return R.error(ErrorCode.NOT_LOGIN);
        }
        Integer res= userService.doLogout(request);
        return R.ok(res);
    }

    @GetMapping("/current")
    public R<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new CommonException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        // TODO 校验用户是否合法
        User user = userService.getById(userId);
        User safetyUser = userService.getSafeUser(user);
        return R.ok(safetyUser);
    }

    /**
     * 分页查询
     * @param request
     * @return
     */
    @GetMapping("/recommend")
    public R<Page<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String redisKey = String.format("bard:user:recommend:%s", loginUser.getId());
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 如果有缓存，直接读缓存
        Page<User> userPage = (Page<User>) valueOperations.get(redisKey);
        if (userPage != null) {
            return R.ok(userPage);
        }
        // 无缓存，查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        // 写缓存
        try {
            valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        return R.ok(userPage);
    }

    /**
     * 根据标签搜索用户
     * @param tagNameList
     * @return
     */
    @GetMapping("/search/tags")
    public R<List<UserVO>> getTagsUserList(@RequestParam(value = "tagNameList",required = false) List<String> tagNameList) {
        log.info("tagNameList:{}",tagNameList);
        if (tagNameList == null || tagNameList.isEmpty()) {
            return R.error(ErrorCode.PARAMS_ERROR); // 自定义错误代码
        }
        log.info("tagNameList:{}",tagNameList);
        List<User> tagsUserList = userService.getTagsUserList(tagNameList);
        if (tagsUserList == null){
            return R.error(ErrorCode.NULL_ERROR);
        }
        //转换成VO
        List<UserVO>userVOS=new ArrayList<>();
        for (User user : tagsUserList) {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            userVOS.add(userVO);
        }
        return R.ok(userVOS);
    }

    @PostMapping("/update")
    public R<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            return R.error(ErrorCode.PARAMS_ERROR);
        }
        User loginUser= userService.getLoginUser(request);
        int res = userService.updateUser(user, loginUser);
        return R.ok(res);
    }
    @GetMapping("/match")
    public R<List<UserVO>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new CommonException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        return R.ok(userService.matchUsers(num, loginUser));
    }

}
